const { Sequelize } = require('sequelize');

const Floorplan = require('./define/Floorplan');
const FloorplanImage = require('./define/FloorplanImage');
const FloorplanMergeImage = require('./define/FloorplanMergeImage');

const { FK } = require('./utils');

module.exports = async function sequelize(options) {
	const { schema, username, password, host, port } = options;

	const sequelize = new Sequelize(schema, username, password, {
		host,
		port,
		dialect: 'mysql',
		define: {
			underscored: true,
			timestamps: false,
			freezeTableName: true
		},
		dialectOptions: {
			connectTimeout: 120000
		},
		logging: () => { }
	});

	[Floorplan, FloorplanImage, FloorplanMergeImage].forEach(item => {
		item(sequelize, options.namespace);
	});

	const Model = {
		Floorplan: sequelize.model('Floorplan'),
		FloorplanImage: sequelize.model('FloorplanImage'),
		FloorplanMergeImage: sequelize.model('FloorplanMergeImage')
	};

	Model.Floorplan.hasMany(Model.FloorplanImage, FK('fpid', { as: 'image', sourceKey: 'fpid' }));
	Model.FloorplanImage.belongsTo(Model.Floorplan, FK('fpid', { as: 'image', sourceKey: 'fpid' }));

	Model.Floorplan.hasMany(Model.FloorplanMergeImage, FK('fpid', { as: 'mergeImage', sourceKey: 'fpid' }));
	Model.FloorplanMergeImage.belongsTo(Model.Floorplan, FK('fpid', { as: 'mergeImage', sourceKey: 'fpid' }));

	return { sequelize, Model };
};